<template>
  <ElDrawer v-model="opened" title="角色绑定权限" @close="closeHandler">
    <ElSkeleton v-if="loading" animated :rows="10" />
    <div>
      <!-- <ElButton type="primary" plain :icon="Expand" @click="onExpandClicked">展开全部</ElButton> -->
      <!-- <ElButton type="primary" plain :icon="Fold" @click="onFoldClicked">收起全部</ElButton> -->
    </div>
    <div class="tree">
      <ElTree
        ref="treeRef"
        :data="treeData"
        show-checkbox
        :default-expanded-keys="expandedKeys"
        node-key="id"
        highlight-current
        :props="defaultProps" />
    </div>

    <template #footer>
      <ElButton type="primary" @click="onSaveClicked">保存</ElButton>
      <ElButton @click="onCancelClicked">关闭</ElButton>
    </template>
  </ElDrawer>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { ElMessage, ElTree } from 'element-plus'
import { setPermissions, getPermissionKeys } from '@api/uc/role'
import { treeMenus } from '@/api/modules/uc/menu'
import { TreeNode } from '@/api/interface'
const defaultProps = {
  children: 'children',
  label: 'name',
  value: 'id'
}
const treeRef = ref<InstanceType<typeof ElTree>>()
const treeData = ref<TreeNode[]>()
const opened = ref(false)
const loading = ref(true)
defineEmits(['success'])
const expandedKeys = ref<string[]>([])
let defaultExpandedKeys: string[]
let roleId = ''
// 打开表单
async function open(id: string) {
  opened.value = true
  roleId = id
  try {
    const {
      data: { records }
    } = await treeMenus()
    treeData.value = records
    defaultExpandedKeys = []
    if (treeData.value) {
      toggleExpand(treeData.value)
    }
    loading.value = false
    const { data } = await getPermissionKeys(id)
    const checked = data ? data : []
    setCheckedKeys(checked as string[])
  } finally {
    loading.value = false
  }
}

// 展开
// function onExpandClicked() {
//   expandedKeys.value = defaultExpandedKeys
// }

// 收起
// function onFoldClicked() {
//   expandedKeys.value = []
// }

// 展开方法递归
function toggleExpand(data: TreeNode[]) {
  data.forEach(item => {
    defaultExpandedKeys.push(item.id)
    if (item.children) {
      toggleExpand(item.children)
    }
  })
}

// 关闭回调
function closeHandler() {
  treeRef.value?.setCheckedKeys([], false)
}

// 获取节点
function getCheckedKeys() {
  return treeRef.value?.getCheckedKeys(false).concat(treeRef.value?.getHalfCheckedKeys()) as string[]
}

// 设置节点
function setCheckedKeys(checkedNode: string[]) {
  const checkedKeys: string[] = []
  resolveAllLeafs(checkedKeys, treeData.value, checkedNode)
  return treeRef.value?.setCheckedKeys(checkedKeys, false)
}

// 解析所有叶子
function resolveAllLeafs(result: string[], nodes?: TreeNode[], checked?: string[]) {
  if (!nodes || !checked) {
    return result
  }
  for (let i = 0; i < nodes.length; i++) {
    const item = nodes[i]
    // 存在子节点，递归遍历;不存在子节点，将json的id添加到临时数组中
    if (item.children && item.children.length !== 0) {
      resolveAllLeafs(result, item.children, checked)
    } else {
      const id = checked.find(id => id === item.id)
      if (id) result.push(id)
    }
  }
  return result
}

// 关闭表单
function close() {
  loading.value = true
  opened.value = false
}

// 保存按钮
function onSaveClicked() {
  const checkedKeys = getCheckedKeys()
  setPermissions(checkedKeys, roleId).then(() => {
    success()
    close()
  })
}

// 成功弹出提示
function success() {
  ElMessage({
    type: 'success',
    message: `成功!`
  })
}

// 取消按钮
function onCancelClicked() {
  close()
}

// 保存成功发送成功事件
// function sendSuccess() {
//   emit('success')
// }

defineExpose({
  open,
  close
})
</script>
<style lang="scss" scoped>
.tree {
  margin-top: 20px;
}
</style>
